#!/bin/bash
if [ -z "$1" ] ; then
  BASE=`echo $(dirname $(readlink -f $0))`
else
  BASE=$1;
fi
export BASE

pidfile=${BASE}/pid
PROXY_CFG=$BASE/assp.cfg

# Override pidfile if a name is given in assp.cfg
if [ -f ${PROXY_CFG} ] ; then
  pidfile="`grep "^pidfile.*=" ${PROXY_CFG} | sed -e 's/pidfile.*=//g'`"
fi
echo "${pidfile}" | grep -q '/' || pidfile=${BASE}/${pidfile}

# create pidfile if a process is already running on this directory
if [ ! -f ${pidfile} ] ; then
  PROGID="`ps -ef | grep "${BASE}/[a]ssp.pl" | awk '{print $2}'`"
  [ -z "${PROGID}" ] || echo -n "${PROGID}" >${pidfile}
fi

if [ ! -f "${pidfile}" ] ; then
  echo "ASSP Anti-SPAM Proxy server in $BASE already stopped"
else
  PROGID=`cat $pidfile | tr -cd [0-9]`
  if [ -z ${PROGID} ] ; then
    echo "${pidfile} does NOT contain a process ID"
    rm -f "${pidfile}"
    exit 1
  elif ps --pid ${PROGID} | grep -q "[a]ssp" ; then
    n=1
    echo -n "Stopping assp (${PROGID}) in ${BASE}"
    while ps ${PROGID} 2>&1 >/dev/null ; do
      echo -n "."
      kill ${PROGID}
      sleep 2
      if [ $(($n % 10)) -eq 0 ] ; then
        kill -9 ${PROGID} 2>&1 >/dev/null
        rm -f "${pidfile}" 2>/dev/null
        if [ $n -gt 30 ] && ps ${PROGID} 2>&1 >/dev/null ; then
          echo "Unable to kill assp (${PROGID})" >&2
          exit 1
        fi
      fi
      let n+=1
    done
    echo ""
  else
    echo "PID: ${PROGID} is not assp"
    exit 1
  fi
fi
exit 0


